// Copyright 2012 Square, Inc.
package com.kanche.bigbaby.collection;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.kanche.bigbaby.BigBabyApplication;
import com.kanche.bigbaby.collection.domain.Photo;
import com.squareup.otto.Bus;

import retrofit.RetrofitError;

//import com.kkche.bss.BigBabyApplication;
//import com.kkche.bss.domain.Photo;

public class ImageUploadTaskService extends Service implements ImageUploadTask.Callback {
    private static final String TAG = "ImageUploadTaskService";

    ImageUploadTaskQueue queue;
    Bus bus;

    private boolean running;

    @Override
    public void onCreate() {
        BigBabyApplication application = ((BigBabyApplication) getApplication());
        bus = application.getBus();
        queue = application.getQueue();
        super.onCreate();
        Log.i(TAG, "Service starting!");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        executeNext();
        return START_STICKY;
    }

    private void executeNext() {
        if (running) return; // Only one task at a time.
        if (queue == null) return;
        ImageUploadTask task = queue.peek();
        if (task != null) {
            running = true;
            task.execute(this);
        } else {
            Log.i(TAG, "Service stopping!");
            stopSelf(); // No more tasks are present. Stop.
        }
    }

    @Override
    public void onSuccess(final Photo photo, long batchId) {
        running = false;
        queue.remove();
        bus.post(new ImageUploadSuccessEvent(photo, batchId));
        executeNext();
    }

    @Override
    public void onFailure(RetrofitError error, Photo photo, long batchId) {
        running = false;
//        Guard.handleError(getApplication(), error);
        bus.post(new ImageUploadFailureEvent(error, photo, batchId));
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
